#!/bin/bash
# moparse-rs 构建脚本

set -e

echo "=== moparse-rs 构建脚本 ==="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 函数：打印带颜色的消息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Rust 是否安装
if ! command -v cargo &> /dev/null; then
    print_error "Rust 未安装，请先安装 Rust："
    echo "  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
    exit 1
fi

print_info "Rust 版本: $(rustc --version)"
print_info "Cargo 版本: $(cargo --version)"

# 解析命令行参数
# 默认使用 musl 静态编译以兼容 CentOS 7（GLIBC 2.17）
BUILD_TYPE=${1:-musl}
TARGET=${2:-}

# 清理旧版本
if [ "$BUILD_TYPE" == "clean" ]; then
    print_info "清理构建文件..."
    cargo clean
    print_info "清理完成"
    exit 0
fi

# 运行测试
if [ "$BUILD_TYPE" == "test" ]; then
    print_info "运行测试..."
    cargo test
    print_info "测试通过"
    exit 0
fi

# 构建
print_info "开始构建 ($BUILD_TYPE 模式)..."

if [ "$BUILD_TYPE" == "debug" ]; then
    cargo build
    BINARY_PATH="target/debug/mo"
elif [ "$BUILD_TYPE" == "release" ]; then
    if [ -n "$TARGET" ]; then
        # 指定目标平台
        print_info "目标平台: $TARGET"
        
        # 检查目标是否已安装
        if ! rustup target list | grep -q "$TARGET (installed)"; then
            print_warn "目标 $TARGET 未安装，正在安装..."
            rustup target add $TARGET
        fi
        
        cargo build --release --target=$TARGET
        BINARY_PATH="target/$TARGET/release/mo"
    else
        cargo build --release
        BINARY_PATH="target/release/mo"
    fi
elif [ "$BUILD_TYPE" == "musl" ]; then
    # 静态链接版本（CentOS 7 推荐，默认）
    print_info "构建静态链接版本（musl）- 兼容 CentOS 7 GLIBC 2.17"
    
    if ! rustup target list | grep -q "x86_64-unknown-linux-musl (installed)"; then
        print_warn "musl 目标未安装，正在安装..."
        rustup target add x86_64-unknown-linux-musl
    fi
    
    # 静态编译，零依赖
    cargo build --release --target=x86_64-unknown-linux-musl
    BINARY_PATH="target/x86_64-unknown-linux-musl/release/mo"
    
    # 验证静态链接
    if command -v file &> /dev/null; then
        print_info "文件类型:"
        file $BINARY_PATH
    fi
    if command -v ldd &> /dev/null; then
        print_info "依赖检查:"
        ldd $BINARY_PATH 2>&1
    fi
elif [ "$BUILD_TYPE" == "static" ]; then
    # 完全静态链接版本（推荐）
    print_info "构建完全静态链接版本..."
    
    if ! rustup target list | grep -q "x86_64-unknown-linux-musl (installed)"; then
        print_warn "musl 目标未安装，正在安装..."
        rustup target add x86_64-unknown-linux-musl
    fi
    
    # 完全静态编译
    export RUSTFLAGS="-C target-feature=+crt-static"
    cargo build --release --target=x86_64-unknown-linux-musl
    BINARY_PATH="target/x86_64-unknown-linux-musl/release/mo"
    
    # 验证静态链接
    if command -v file &> /dev/null; then
        print_info "文件类型:"
        file $BINARY_PATH
    fi
else
    print_error "未知的构建类型: $BUILD_TYPE"
    echo "用法: $0 [debug|release|musl|static|clean|test] [target]"
    echo ""
    echo "构建类型说明:"
    echo "  musl    - musl 静态链接版本（默认，推荐用于 CentOS 7，零依赖）"
    echo "  release - 优化版本（部分静态链接，需要 GLIBC 2.25+）"
    echo "  static  - 完全静态链接版本（同 musl）"
    echo "  debug   - 调试版本（包含调试信息）"
    echo "  clean   - 清理构庺文件"
    echo "  test    - 运行测试"
    echo ""
    echo "注意: CentOS 7 用户必须使用 'musl' 或 'static' 模式，以避免 GLIBC 版本问题"
    exit 1
fi

# 检查构建结果
if [ -f "$BINARY_PATH" ]; then
    print_info "构建成功！"
    print_info "二进制文件: $BINARY_PATH"
    
    # 显示文件信息
    ls -lh $BINARY_PATH
    
    # 检查依赖（仅 Linux）
    if command -v ldd &> /dev/null && [ -z "$TARGET" ]; then
        print_info "依赖检查:"
        ldd $BINARY_PATH || true
    fi
    
    # 运行版本检查
    print_info "版本信息:"
    $BINARY_PATH --version || true
    
    # 拷贝到 modb 目录
    MODB_DIR="$(cd "$(dirname "$0")/.." && pwd)"
    if [ -d "$MODB_DIR" ]; then
        print_info "拷贝可执行文件到 modb 目录..."
        cp $BINARY_PATH $MODB_DIR/mo
        chmod +x $MODB_DIR/mo
        print_info "已拷贝到: $MODB_DIR/mo"
        ls -lh $MODB_DIR/mo
    else
        print_warn "modb 目录不存在，跳过拷贝"
    fi
else
    print_error "构建失败！"
    exit 1
fi

echo ""
print_info "=== 构建完成 ==="
print_info "运行: $BINARY_PATH --help"
if [ -f "$MODB_DIR/mo" ]; then
    print_info "或者: $MODB_DIR/mo --help"
fi
